<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    @ok="handleOK"
   :title="t('sys.script.details')"
  >
    <Description :column="1" :data="mockData" :schema="schema" />
    <div class="tabelview">
      <BasicTable @register="registerTableModel">
        <template #resetBefore>
          <Button @click="toggleSelectAll" style="margin-right: 10px">
            <template #icon>
              <CheckOutlined v-if="isAllSelected" />
              <CloseOutlined v-else />
            </template>
            全选
          </Button>
        </template>
      </BasicTable>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { Description, DescItem } from '@/components/Description';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { ref, computed, h } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { getDetailAPI, getMatchMaxAPI, matchListAPI } from '@/api/demo/InformationMatching';
  import { columnsModels } from './account.data';
  import { Progress, Tooltip, Button } from 'ant-design-vue';
  import { CheckOutlined, CloseOutlined } from '@ant-design/icons-vue';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  const emit = defineEmits(['success']);
  const Data = ref<any>({});
  const dataSource = ref<any[]>([]);
  const buttonLabels = ref<{ label: string; value: number }[]>([]);
  const mockData = ref({});
  const isAllSelected = ref(false);
  const selectedLabels = ref<string[]>([]);
  defineOptions({ name: 'AccountModal' });
  const schema: DescItem[] = [
    { field: 'title', label: t('sys.informaionMatchaing.columns.title'), labelMinWidth: 150 },
    { field: 'remark', label: t('sys.configuration.describe'), labelMinWidth: 150 },
    {
      field: 'status',
      label: t('sys.informaionMatchaing.columns.status'),
      labelMinWidth: 150,
      render: (val: any, data: Recordable) => {
        if (data.status === t('sys.configuration.inProgress')) {
          if (data.status1 !== t('sys.configuration.taskSucces')) {
            return `一阶段状态 ${data.status1}`;
          } else {
            return `二阶段状态 ${data.status2}`;
          }
        }
        return data.status;
      },
    },
    {
      field: 'type',
      label: t('sys.informaionMatchaing.columns.type'),
      labelMinWidth: 150,
      render: (val: any, data: Recordable) => {
        return data.type === 'orientation' ? t('sys.informaionMatchaing.columns.orientation') : t('sys.informaionMatchaing.columns.match');
      },
    },
    {
      field: 'currentNode',
      label: t('sys.informaionMatchaing.columns.currentNode'),
      labelMinWidth: 150,
      render: (val: any, data: Recordable) => {
        const currentNode = data.currentNode ?? '-';
        const maxNode = data.maxNode ?? '-';
        return `${currentNode}/${maxNode}`;
      },
    },
    {
      field: 'success',
      label: t('sys.informaionMatchaing.columns.success'),
      labelMinWidth: 150,
      render: (val: any, data: Recordable) => {
        const success = data.success ?? '-';
        const maxNum = data.maxNum ?? '-';
        return `${success}/${maxNum}`;
      },
    },
  ];
  const searchFormSchemaDtail = ref([
    {
      field: 'matching',
      label: t('sys.informaionMatchaing.columns.matching'),
      component: 'Input',
      colProps: { span: 4 },
      defaultValue: '0.2',
    },
    {
      field: 'customButtons',
      label: '',
      component: 'Input',
      colProps: { span: 18 },
      render: ({ model, field }) => {
        return h(
          'div',
          {
            style: { width: '80vw' },
          },
          buttonLabels.value.map((item, index) =>
            h(
              Button,
              {
                key: index,
                onClick: () => handleButtonClick(model, field, item),
                style: { marginLeft: '10px' },
              },
              `${item.label} : 数量${item.value}`,
            ),
          ),
        );
      },
    },
  ]);

  const isUpdate = ref(true);
  const modalWidth = ref('60%');
  interface FormSchema {
    field: string;
    label: string;
    component: string;
    colProps: { span: number };
    defaultValue?: string;
    render?: ({ model, field }: { model: any; field: string }) => VNode;
  }
  const [registerTableModel, { reload, setSelectedRowKeys, getSelectRows, clearSelectedRowKeys }] =
    useTable({
      api: ({ page, pageSize, matching }) =>
        getDetailAPI({ ...Data.value, page, pageSize, matching }),
      rowKey: 'dataId',
      columns: columnsModels,
      showTableSetting: true,
      bordered: true,
      handleSearchInfoFn(info) {
        return info;
      },
      formConfig: {
        schemas: searchFormSchemaDtail,
        autoSubmitOnEnter: true,
        labelAlign: 'left',
      },
      useSearchForm: true,
      rowSelection: {
        type: 'checkbox',
      },
    });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    Data.value = data.record;
    mockData.value = data.record;
    dataSource.value = [Data.value];
    getMatchMax();
    setModalProps({ confirmLoading: false, showOkBtn: true });
    await reload();
  });

  async function handleOK() {
    const selectedRows = getSelectRows();
    const urls = selectedRows.map((row) => row.url).filter((url) => url);
    const combinedUrls = [...urls, ...selectedLabels.value];
    emit('success', { urls: combinedUrls });
    closeModal();
  }

  async function getMatchMax() {
    let valueData = await getMatchMaxAPI(Data.value.id);
    buttonLabels.value = valueData.data.map((item) => ({
      label: Number(item.label).toFixed(2),
      value: item.value,
    }));
  }

  const handleButtonClick = (model, field, label) => {
    model.matching = label.label;
  };

  const toggleSelectAll = async () => {
    isAllSelected.value = !isAllSelected.value;
    if (isAllSelected.value) {
      let value = await matchListAPI({
        ...Data.value,
        matching: searchFormSchemaDtail.value[0].defaultValue,
      });
      selectedLabels.value = value.data.map((item: { label: string }) => item.label);
      // 更新表格的选中状态
      let setSelectedRowKeysNum = [];

      value.data.forEach((item) => {
        setSelectedRowKeysNum.push(Number(item.value));
      });
      setSelectedRowKeys(setSelectedRowKeysNum);
    } else {
      selectedLabels.value = [];
      clearSelectedRowKeys();
    }
  };
</script>

<style scoped>
  .tabelview :deep(.vben-basic-table-form-container .ant-form) {
    margin: 0 !important;
    padding-bottom: 0 !important;
  }
</style>
